package me.chan.nio.base;

import java.nio.ByteBuffer;

import static me.chan.nio.util.ByteBufferUtils.display;

public class ByteBufferDemo {

    public static void main(String[] args) {

        // allocate 16 bytes to show display method pretty-reading
        ByteBuffer buffer = ByteBuffer.allocate(16);
        buffer.put(new byte[]{'1','2','3','4','a','b','c'});
        display(buffer);
        System.out.println("the capacity of this buffer:" + buffer.capacity());
        System.out.println("position before flipping:" + buffer.position());
        System.out.println("limit before flipping:" + buffer.limit());
        buffer.flip();
        System.out.println("================== do flip ==================");
        System.out.println("position after flipping: " + buffer.position());
        System.out.println("limit after flipping: " + buffer.limit());
        System.out.println("current character is: " + (char)buffer.get());  // will get '1'
        System.out.println("current position is: " + buffer.position());  // will point to '2' so that the index of byte array is 1
        System.out.println((char)buffer.get(4)); // will get 'a' but the position will not change and still equal to 1
        System.out.println("current position is: " + buffer.position());  // will get 1
        buffer.rewind();                        // will reset the position to be 0
        System.out.println("current position is: " + buffer.position());  // will get 0

        char ch = (char) buffer.get();
        System.out.println("the current position is: " + buffer.position());
        buffer.mark();      // mark the current position of this buffer
        byte[] des = new byte[4];
        buffer.get(des);    // will read 4 byte and the position will go to index 5
        System.out.println("current position is: " + buffer.position());
        display(buffer);
        buffer.reset();  // make position return to marked before
        display(buffer); // will show the position at index 1
        buffer.rewind();  // reset the position to 0 and clear the mark sign
        display(buffer);
        buffer.clear();     // NOTE: will not actually erase the data in byte array
        buffer.put(new byte[]{'a','b','c','d'});
        display(buffer);
        buffer.flip();
        buffer.get();
        buffer.get();
        buffer.compact();    // switch to writable mode
        display(buffer);     // position will at index 2 cause we called twice get method just now
        buffer.put(new byte[]{'e','f','g'});
        display(buffer);
    }
}
